import axios from 'axios'
import { baseUrl } from "@/config"

// 普通请求超时时间
axios.defaults.timeout = 30000

// create an axios instance
export const service = axios.create({
    baseURL: baseUrl, // url = base url
    retry: 4, // 请求次数
    retryInterval: 1000, // 求期间隙
    headers: {
        'Authorization': 'Basic c2FiZXI6c2FiZXJfc2VjcmV0',
    }
})

// SSE 请求配置
export const sseConfig = {
    headers: {
        'Accept': 'text/event-stream',
        'Cache-Control': 'no-cache',
        'logintoken': localStorage.getItem('token') || ''
    },
    responseType: 'text',
    //timeout: 0,  // 禁用超时
    onDownloadProgress: (progressEvent) => {
        console.log('SSE download progress:', {
            loaded: progressEvent.loaded,
            total: progressEvent.total,
            progress: progressEvent.total ? (progressEvent.loaded / progressEvent.total) * 100 : undefined,
            bytes: progressEvent.loaded,
            rate: progressEvent.rate,
            download: true,
            event: progressEvent
        });
    }
};

service.defaults.validateStatus = function (status) {
    return status >= 200 && status <= 500
};

// request interceptor
service.interceptors.request.use(
    config => {
        // let userInfo = context.$store.state.user.userInfo
        // if (userInfo) {
        //     config.headers['Blade-Auth'] = userInfo.token_type + ' ' + userInfo.access_token
        //     config.headers['Tenant-Id'] = userInfo.tenant_id
        // }
       // console.log('request interceptor:', config)
        const logintoken = localStorage.getItem('token')
        const unicode = localStorage.getItem('unicode')
        if (logintoken) {
            config.headers['logintoken'] = logintoken
        }
        if (config.url.includes('chat/send') && unicode) {
            config.headers['unicode'] = unicode
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// SSE request interceptor
sseConfig.onDownloadProgress = function (progressEvent) {
    console.log('SSE download progress:', progressEvent);
}

// SSE response interceptor
sseConfig.onDownloadProgress = function (progressEvent) {
    console.log('SSE download progress:', progressEvent);
}

// response interceptor
service.interceptors.response.use(
    /**
     * If you want to get http information such as headers or status
     * Please return  response => response
     */

    /**
     * Determine the request status by custom code
     * Here is just an example
     * You can also judge the status by HTTP Status Code
     */
    res => {
        // console.log('Response interceptor:', {
        //     url: res.config.url,
        //     method: res.config.method,
        //     status: res.status,
        //     statusText: res.statusText,
        //     headers: res.headers,
        //     data: res.data,
        //     responseType: res.config.responseType
        // });

        // 如果是 SSE 请求，添加特殊处理
        if (res.config.url.includes('/api/chat/connect')) {
            // console.log('SSE response details:', {
            //     status: res.status,
            //     statusText: res.statusText,
            //     headers: res.headers,
            //     data: res.data,
            //     config: {
            //         headers: res.config.headers,
            //         responseType: res.config.responseType
            //     }
            // });

            // 检查响应头
            const contentType = res.headers['content-type'];
            if (contentType && !contentType.includes('text/event-stream')) {
                console.warn('Unexpected content type for SSE:', contentType);
            }

            // 对于 SSE 请求，直接返回响应
            return res;
        }

        //获取状态码
        const status = res.data.code || res.status;
        const message = res.data.msg || res.data.error_description || res.msg || '未知错误';

        // 检查文件下载响应
        if (res.data.size !== undefined) {
            if (res.data.size < 100) {
                uni.showToast({
                    title: '无文件可供下载!',
                    icon: 'none'
                });
                return Promise.reject(new Error('无文件可供下载'));
            }
        }

        // 处理非 200 状态码
        if (status !== 200) {
            if (status === 500) {
                uni.showToast({
                    title: '网络请求超时，请再试一次',
                    icon: 'none'
                });
            } else if (status === 401) {
                uni.showToast({
                    title: '登录已过期，请重新登录',
                    icon: 'none'
                });
                // 清除本地存储的token
                localStorage.removeItem('token');
                // 跳转到登录页
               
                  window.location.href = '/'
                
            
            } else {
                // uni.showToast({
                //     title: message,
                //     icon: 'none'
                // });
            }
            return Promise.reject(res);
        }

        // 处理正常响应
        if (res.data.hasOwnProperty('data')) {
            if (res.data.data == null || JSON.stringify(res.data.data) == '{}') {
                return {
                    data: '',
                    status,
                    message
                };
            }
            return res.data;
        }
        return res.data;
    },
    error => {
        console.error('Response error:', {
            url: error.config?.url,
            method: error.config?.method,
            status: error.response?.status,
            statusText: error.response?.statusText,
            data: error.response?.data,
            message: error.message,
            config: error.config
        });

        if (error.toString() === 'Error: Network Error') {
            uni.showToast({
                title: '请检查您的网络状态！',
                icon: 'none'
            });
            return Promise.reject('请检查您的网络状态!');
        } else if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1) {
            uni.showToast({
                title: '网络请求超时，请再试一次!',
                icon: 'none'
            });
            return Promise.reject('网络请求超时，请再试一次!');
        }
        return Promise.reject(error);
    }
)

export default service
